package com.rock.code.datacollconfig.zabbix.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.code.datacollconfig.host.dao.TbAssetHostDao;
import com.rock.code.datacollconfig.zabbix.dao.TbCollResConfDao;
import com.rock.code.datacollconfig.zabbix.domain.TbCollResConf;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * Created by zhongqing.han Cotter on 2019/5/21.
 */
public class getAllHost {

    private static ResourceBundle LoginInfo = ResourceBundle.getBundle("zabbix");

    private static String URL;

    private static String PATH;

    private static String AUTH = null;

    private static final String USERNAME;

    private static final String PASSWORD;

    static {
        URL = "http://" + LoginInfo.getString("zabbixserverip") + ":" + LoginInfo.getString("zabbixport") + LoginInfo.getString("zabbixapiurl");
        USERNAME = LoginInfo.getString("user");
        PASSWORD = LoginInfo.getString("pwd");
        PATH = LoginInfo.getString("path");
    }
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
        TbCollResConfDao tbCollResConfDao = (TbCollResConfDao) context.getBean("tbCollResConfDao");
        TbAssetHostDao tbAssetHostDao = (TbAssetHostDao) context.getBean("tbAssetHostDao");

        List<String> ips_old = tbCollResConfDao.getAllCollResIp();
        String swapPath = tbCollResConfDao.getPath();

        List<Map> idAndIp = getHostIdAndIP();
        String hostId = "";
        String ip_new = "";
        String deviceName = "";
        Calendar now = Calendar.getInstance();
        String _now = now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH)+1) + "-" + now.get(Calendar.DAY_OF_MONTH);
        if(idAndIp.isEmpty()){
            System.out.println("没有获取到主机");
        } else {
            List<String> ips_new = new ArrayList<>();
            // 对比新增主机
            for(Map hostIdAndIP : idAndIp){
                hostId = hostIdAndIP.get("hostid").toString();
                ip_new = hostIdAndIP.get("ip").toString();
                deviceName = hostIdAndIP.get("name").toString();
                String hostType = getHostTypeByHostId(hostId);
                String _hostType = hostType.split(" ")[0];
                if(null != _hostType && !"".equals(_hostType)){
                    _hostType = "0".equals(_hostType) ? "Other" : _hostType;
                    if(!ips_old.contains(ip_new)){
                        String path = PATH+"/add/"+_hostType+_now;
                        writeFile(ip_new, path);
                        insert(tbAssetHostDao, tbCollResConfDao, swapPath, _hostType, ip_new, deviceName);
                    }
                }
                ips_new.add(ip_new);

                String path = PATH+_now;
                writeFile(ip_new, path);
            }

            for(String ip_old : ips_old){
                if(!ips_new.contains(ip_old)){
                    String hostType = tbCollResConfDao.getKbpByIp(ip_old);
                    switch(hostType){
                        case "10-10-20":
                            hostType = "AIX";
                            break;
                        case "10-10-21":
                            hostType = "HP-UX";
                            break;
                        case "10-10-23":
                            hostType = "Windows";
                            break;
                        case "10-10-24":
                            hostType = "Linux";
                            break;
                    }
                    String path = PATH+"/del/"+hostType+_now;
                    writeFile(ip_old, path);
                    tbCollResConfDao.delete(ip_old);
                    tbAssetHostDao.delete(ip_old);
                }
            }

            List<String> ips = tbCollResConfDao.getAllCollResIp();
            int i = 1;
            Map<String, String> map = new HashMap<>();
            for(String ip : ips){
                int id = i++;
                map.put("id", id+"");
                map.put("ip", ip);
                tbCollResConfDao.update(map);
            }

        }
    }

    private static String getHostTypeByHostId(String hostId){

        Map<String, Object> search = new HashMap<String, Object>();
        search.put("key_", "system.uname");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("host", hostId);
        params.put("search", search);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "item.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");
        String hostUname = "";
        for(int i=0; i<result.size(); i++){
            hostUname = result.getJSONObject(i).getString("lastvalue");
        }
        return hostUname;
    }

    // 获取主机id&ip
    private static List getHostIdAndIP(){

        List<String> insterfaces = new ArrayList();
        insterfaces.add("ip");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("selectInterfaces", insterfaces);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "host.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        List<Map> IdAndIP = new ArrayList();
        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");

        if(result.size()>0){
            for(int i=0; i<result.size(); i++){
                Map<String, String> hostIdAndIP = new HashMap<>();
                String hostId = result.getJSONObject(i).getString("host");
                String name = result.getJSONObject(i).getString("name");
                JSONArray ipJson = result.getJSONObject(i).getJSONArray("interfaces");
                String ip = ipJson.getJSONObject(0).getString("ip");
                if(ipJson.size() > 1){
                    String[] ips = ip.split(",");
                    ip = ips[0];
                }
                hostIdAndIP.put("hostid", hostId);
                hostIdAndIP.put("ip",ip);
                hostIdAndIP.put("name", name);
                IdAndIP.add(hostIdAndIP);
            }
        } else {
            return null;
        }
        return IdAndIP;
    }

    private static String sendPost(Map map){
        String param = JSON.toJSONString(map);
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        StringBuffer sb = null;
        try {
            //创建连接
            java.net.URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式

            connection.connect();

            //POST请求
            out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(param);
            out.flush();

            //读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();
    }

    private static void setAuth() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", USERNAME);
        params.put("password", PASSWORD);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "user.login");
        map.put("params", params);
        map.put("auth", null);
        map.put("id", 0);

        String response = sendPost(map);
        JSONObject json = JSON.parseObject(response);
        AUTH = json.getString("result");
    }

    private static String getAuth() {
        if (AUTH == null) {
            setAuth();
        }
        return AUTH;
    }

    private static void writeFile(String ip, String path){
        File file = new File(new File(path).getParent());
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true)));
            out.write(ip);
            out.newLine();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void insert(TbAssetHostDao tbAssetHostDao, TbCollResConfDao tbCollResConfDao, String swapPath, String hostType, String ip, String deviceName){

        // insert into TB_COLL_RESOURCE_CONF
        TbCollResConf tbCollResConf = new TbCollResConf();
        tbCollResConf.setId(Math.random()*600+"");
        tbCollResConf.setColl_name("zabbix采集");
        tbCollResConf.setResource_name(ip);
        tbCollResConf.setIp(ip);
        tbCollResConf.setResource_type("1");
        tbCollResConf.setColl_type("1");
        tbCollResConf.setResource_desc("采集zabbix");
        tbCollResConf.setEnable("1");
        tbCollResConf.setPath(swapPath);
        if("AIX".equals(hostType)){
            tbCollResConf.setKbp("10-10-20");
            tbCollResConfDao.insert(tbCollResConf);
        }
        if("HP-UX".equals(hostType)){
            tbCollResConf.setKbp("10-10-21");
            tbCollResConfDao.insert(tbCollResConf);
        }
        if("Windows".equals(hostType)){
            tbCollResConf.setKbp("10-10-23");
            tbCollResConfDao.insert(tbCollResConf);
        }
        if("Linux".equals(hostType)){
            tbCollResConf.setKbp("10-10-24");
            tbCollResConfDao.insert(tbCollResConf);
        }

        // insert into itnmsdb.TB_ASSET_HOST
        Map<String, String> map = new HashMap<>();
        String deviceId = ip.replace(".", "_");
        String ipAddr = ip;
        String _deviceName = deviceName;
        if("AIX".equals(hostType)){
            String unitId = "10-10-20:"+deviceId;
            String type = "IBM";
            String kbpClass = "10-10-20";
            map.put("unitId", unitId);
            map.put("ipAddr", ipAddr);
            map.put("deviceId", deviceId);
            map.put("hostType", type);
            map.put("kbpClass", kbpClass);
            map.put("deviceName", _deviceName);
            tbAssetHostDao.insert(map);

        }
        if("HP-UX".equals(hostType)){
            String unitId = "10-10-21:"+deviceId;
            String type = "HP";
            String kbpClass = "10-10-21";
            map.put("unitId", unitId);
            map.put("ipAddr", ipAddr);
            map.put("deviceId", deviceId);
            map.put("hostType", type);
            map.put("kbpClass", kbpClass);
            map.put("deviceName", _deviceName);
            tbAssetHostDao.insert(map);
        }
        if("Windows".equals(hostType)){
            String unitId = "10-10-23:"+deviceId;
            String type = "MicroSoft";
            String kbpClass = "10-10-23";
            map.put("unitId", unitId);
            map.put("ipAddr", ipAddr);
            map.put("deviceId", deviceId);
            map.put("hostType", type);
            map.put("kbpClass", kbpClass);
            map.put("deviceName", _deviceName);
            tbAssetHostDao.insert(map);
        }
        if("Linux".equals(hostType)){
            String unitId = "10-10-24:"+deviceId;
            String type = "REDHAT";
            String kbpClass = "10-10-24";
            map.put("unitId", unitId);
            map.put("ipAddr", ipAddr);
            map.put("deviceId", deviceId);
            map.put("hostType", type);
            map.put("kbpClass", kbpClass);
            map.put("deviceName", _deviceName);
            tbAssetHostDao.insert(map);
        }

    }

}

